/**
 * TranslateServlet.java
 *
 * Copyright (C) 2009,  Tomislav Milkovic
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package extjsdyntran.servlets;

import java.io.*;
import java.lang.reflect.Type;
//import java.net.Authenticator;
import java.util.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import ws4is.servlets.engine.AbstractActionDispatcherServlet;
import ws4is.servlets.engine.HTTPRequestType;

import extjsdyntran.translation.TranslationFactory;
import extjsdyntran.translation.store.StoreManager;



/**
 * @description  Main translation servlet responsible for initialization of translation services and
 * translations itself
 */
public final class TranslateServlet extends AbstractActionDispatcherServlet{
	
	final Logger logger = LoggerFactory.getLogger(TranslateServlet.class);
	private static final long serialVersionUID = 1L;
	
	public TranslateServlet() throws Exception {
		super();
	}
	
	public void destroy() {
		TranslationFactory.saveLanguages("*");
		super.destroy();
	}

	public void init(ServletConfig conf) throws ServletException {
		super.init(conf);
		Gson gs = new Gson();		
		
		logger.info("Loading configuration for translation servlet...");
		//store param is saved in json format, deserialize it
		String stsvcp = conf.getInitParameter(Constants.prop_store_parm);		
		Type typeOfMap = new TypeToken<HashMap<String,String>>(){}.getType();
		HashMap<String, String> params = gs.fromJson(stsvcp, typeOfMap);
		
		
		String path =  params.get(Constants.param_path);
		path=getPath(path);
		params.put(Constants.param_path, path);
		logger.info("Loading store services...");
		loadStore(conf,gs,params);
		logger.info("Loading translation services...");
		loadServices(conf,gs,path);	
		if (TranslationFactory.size()==0) {
			logger.error("There is no translation services initialized!!!");
			new ServletException("Translation service not set!");		
		}
		
	}
		 
	private String getPath(String path){
		String store = path;
		File file = new File(path);
		if (!file.exists()) {
			
			String value = ((File) getServletContext().getAttribute("javax.servlet.context.tempdir")).getPath();
			store = value + System.getProperty("file.separator");
			
			String[] msg = {"Directroy does not exists for..." , 
							"property : " + Constants.prop_store_path,
							"and value: " + path,
							"Using server temporary path : " + value
							};			
			
			logger.warn(" \n {}\n {}\n {}\n {}\n",msg);
		}
		return store;
	}
	
	
	private void loadStore(ServletConfig conf, Gson gs, HashMap<String, String> params)throws ServletException{
				
		try {
			String stsvc = conf.getInitParameter(Constants.prop_store);
			Class cls = Class.forName(stsvc);

			if (!StoreManager.initStore(cls, params)) {
				logger.error("Translation store service not set for class " + stsvc);
				new ServletException("Translation store service not set!");
			}
		} catch (ClassNotFoundException e) {
			 logger.error(e.getMessage());
			 new ServletException(e);
		}
	}
	
	private void loadServices(ServletConfig conf, Gson gs,String path)throws ServletException{
		
		String json_services = conf.getInitParameter(Constants.prop_services);
		String[] svcs = gs.fromJson(json_services, String[].class);
		for(String value :svcs){
			try{
				TranslationFactory.appendService( value,
											  (String) conf.getInitParameter(Constants.prop_proxy_user),
											  (String) conf.getInitParameter(Constants.prop_proxy_password),
											  path);
				}catch(Exception e){
					logger.error("Error initializing translation service : " + value + "; message :" + e.getMessage());
					new ServletException(e);
				}
		}
	}

	/******************************************
	 * 			overrides        		      * 
	 ******************************************/

	@Override
	public void postAction(HTTPRequestType type, String method, Exception e) {
		// TODO event handling after response is sent to client; for example..auto save etc..
	}


	//set URL parameter used to route requests to specified actions
	// if action=EditorActions then class named EditorActions will be used for data processing
	// each action class need to provide parameter containing methodname to execute
	// see at Actions preExecute method
	@Override
	public String preAction(HTTPRequestType type, HttpServletRequest request) {
		return "action";
	}
}
